package com.xhis.homenurse.tools;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.xhis.homenurse.models.Base_in;
import com.xhis.homenurse.webservice.api.ContactNet;
import com.xhis.homenurse.webservice.ksoap2.transport.SoapHelper;

import org.json.JSONObject;

import java.net.URLEncoder;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by 张兵 on 2019/7/17.
 */
public class XmlFormatUtils
{
    /*
    * map转xml map中没有根节点的键
    * @param hashMap
    * @param rootName
    * @throws DocumentException
    * @throws IOException
    */
//    public static String hashMap2Xml(LinkedHashMap<String, Object> hashMap, String rootName) throws DocumentException, IOException {
//        Document doc = DocumentHelper.createDocument();
//        Element root = DocumentHelper.createElement(rootName);
//        doc.add(root);
//        map2Xml(hashMap, root);
//        return formatXml(doc);
//    }

    /**
     * 格式化输出xml
     */
//    public static String formatXml(Document document) throws IOException {
//        OutputFormat format = OutputFormat.createPrettyPrint();
//        format.setSuppressDeclaration(true);
//        StringWriter writer = new StringWriter();
//        XMLWriter xmlWriter = new XMLWriter(writer, format);
//        xmlWriter.write(document);
//        xmlWriter.close();
//        return writer.toString();
//    }


    /**
     * map转xml
     *
     * @param map
     * @param body xml元素
     * @return
     */
//    private static Element map2Xml(LinkedHashMap<String, Object> map, Element body) {
//        Iterator<Map.Entry<String, Object>> entries = map.entrySet().iterator();
//        while (entries.hasNext()) {
//            Map.Entry<String, Object> entry = entries.next();
//            String key = entry.getKey();
//            Object value = entry.getValue();
//            if (key.startsWith("@")) {
//                body.addAttribute(key.substring(1, key.length()), value.toString());
//            } else if (key.equals("#text")) {
//                body.setText(value.toString());
//            } else {
//                if (value instanceof List) {
//                    List list = (List) value;
//                    Object obj;
//                    for (int i = 0; i < list.size(); i++) {
//                        obj = list.get(i);
//                        if (obj instanceof Map) {
//                            Element subElement = body.addElement(key);
//                            map2Xml((LinkedHashMap) list.get(i), subElement);
//                        } else {
//                            body.addElement(key).setText((String) list.get(i));
//                        }
//                    }
//                } else if (value instanceof Map) {
//                    Element subElement = body.addElement(key);
//                    map2Xml((LinkedHashMap) value, subElement);
//                } else {
//                    body.addElement(key).setText(value.toString());
//                }
//            }
//        }
//        return body;
//    }

    public static String formatInputData(String input) {
        return input .replaceAll("n0:", "").replaceAll(":n0", "");
    }

    public static String requestParams (Base_in baseIn) {
        String requestBody = "";
        try {
            //参数
            LinkedHashMap<String, Object> properties = new LinkedHashMap<String, Object>();
            String inputData = baseIn.getInputData();
            properties.put("inputData", inputData);
            properties.put("guid", UUID.randomUUID().toString());
            String content = properties.toString();
            Log.e("SoapRequestProperties", content);
            LogUtil.saveLog("request",inputData);
            //参数封装
            List<Object> getParamters = SoapHelper.getInstance().getParams(ContactNet.METHODNAME, ContactNet.NAMESPACE, properties);
            if (getParamters != null) {
                //soapHeaderMap = (Map<String, String>) getParamters.get(0);
                requestBody = formatInputData(new String((byte[]) getParamters.get(1)));
            }
        } catch (Exception e) {

        }
        return requestBody;
    }

    public static String requestParams_Http(Base_in base_in){
        String requestBody = "";
        LinkedHashMap<String, Object> properties = new LinkedHashMap<String, Object>();
        try {
//            Field [] fields = base_in.getClass().getDeclaredFields();
//            for(Field tempField : fields){
//                if(tempField.getGenericType().toString().equals("class java.lang.String")) {
//                    tempField.setAccessible(true);
//                    properties.put(tempField.getName(), tempField.get(base_in));
//                }
//            }
//            properties.put("czy", WSProxy.userName);
//            properties.put("token",WSProxy.token);
//            properties.put("guid", UUID.randomUUID().toString());
            properties.put("inputData", URLEncoder.encode(URLEncoder.encode(base_in.getInputData(),"UTF-8"),"UTF-8"));
            Iterator iter = properties.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                if(TextUtils.isEmpty(requestBody)){
                    requestBody = entry.getKey()+"="+entry.getValue();
                }else{
                    requestBody += "&"+entry.getKey()+"="+entry.getValue();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return requestBody;
    }


    public static String requestParams_Gson(Base_in base_in){
        String requestBody = "";
        LinkedHashMap<String, Object> properties = new LinkedHashMap<String, Object>();
        try {
            Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
            String gsonString = gson.toJson(base_in);
            JSONObject object = new JSONObject(gsonString);
            Iterator<String> keys = object.keys();
            while(keys.hasNext()){
                String key = keys.next();
                properties.put(key,object.getString(key));
            }
//            properties.put("guid", UUID.randomUUID().toString());
            Iterator iter = properties.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                if(TextUtils.isEmpty(requestBody)){
                    requestBody = entry.getKey()+"="+entry.getValue();
                }else{
                    requestBody += "&"+entry.getKey()+"="+entry.getValue();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return requestBody;
    }
}
